package com.luoke.service.response.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.luoke.connect.GameWebSocketClient;
import com.luoke.constants.ModuleTypeConstant;
import com.luoke.constants.StatusConstant;
import com.luoke.constants.SubmoduleTypeConstant;
import com.luoke.context.UserContext;
import com.luoke.handler.request.BattleRequestHandler;
import com.luoke.handler.request.UserRequestHandler;
import com.luoke.manage.threadmanage.FutureManager;
import com.luoke.pojo.dto.BagDTO;
import com.luoke.pojo.entity.Goods;
import com.luoke.pojo.entity.Map;
import com.luoke.pojo.entity.Pet;
import com.luoke.pojo.entity.Skill;
import com.luoke.pojo.entity.User;
import com.luoke.service.response.UserResponseService;
import com.luoke.result.Result;
import jdk.nashorn.internal.objects.Global;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 用户响应服务层 ，处理服务端发送的响应
 */
@Slf4j
public class UserResponseServiceImpl implements UserResponseService {

    private UserRequestHandler userRequestHandler = new UserRequestHandler();
    private BattleRequestHandler battleRequestHandler = new BattleRequestHandler();


    /**
     * 处理登录请求后的服务端响应
     *
     * @param gameWebSocketClient 使用该对象与服务端通信
     * @param result              服务端返回的结果
     */
    @Override
    public void userLogin(GameWebSocketClient gameWebSocketClient, Result result) {
        if (result.getStatus().equals("success")) {
            List<Pet> currentPet = result.getCurrentPet();
            result.setData(JSONUtil.toBean(result.getData().toString(), User.class));
            User data = (User) result.getData();
            System.out.println(result.getMessage()); //登录成功，展示服务端返回的登录成功的消息
            UserContext.setCurrentUser(data.getName());  //把登录用户的信息设置到全局
            UserContext.setUser(data);
            UserContext.setUserPet(currentPet);
            UserContext.setUserBag(result.getCurrentBag());
            battleRequestHandler.showGameMenu(gameWebSocketClient); //登录成功之后转跳到游戏界面


        } else {
            System.out.println(result.getMessage());
            userRequestHandler.showLoginMenu(gameWebSocketClient);  //登录失败，则重新回到登录菜单界面
        }

    }

    /**
     * 处理注册请求后的服务端响应
     *
     * @param gameWebSocketClient 使用该对象与服务端通信
     * @param result              服务端返回的结果
     */
    @Override
    public void userRegister(GameWebSocketClient gameWebSocketClient, Result result) {

        if (result.getStatus().equals(StatusConstant.SUCCESS)) {
            System.out.println(result.getMessage());
        } else {
            System.out.println(result.getMessage());//注册失败，展示原因
        }

        userRequestHandler.showLoginMenu(gameWebSocketClient);//无论成功还是失败，转跳回登录页面
    }

    /**
     * 对服务端的注销响应进行处理
     *
     * @param gameWebSocketClient 使用该对象与服务端通信
     * @param result              服务端返回的结果
     */
    @Override
    public void userLogout(GameWebSocketClient gameWebSocketClient, Result result) {
        if (result.getStatus().equals(StatusConstant.SUCCESS)) {
            System.out.println(result.getMessage());
            UserContext.clear();
            userRequestHandler.showLoginMenu(gameWebSocketClient);
        }
    }

    /**
     * 对服务端显示背包的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    @Override
    public void showBag(GameWebSocketClient gameWebSocketClient, Result result) {
        JSONArray objects = JSONUtil.parseArray(result.getData());
        System.out.println("-----------查看背包----------");
        for (int i = 0; i < objects.size(); i++) {
            BagDTO bag = objects.get(i, BagDTO.class);
            System.out.println(StrUtil.format("名称：{}，类型：{}，描述：{},数量：{}"
                    , bag.getGoodsName()
                    , bag.getType()
                    , bag.getDescription()
                    , bag.getQuantity()));
        }
        System.out.println("-----------查看背包----------");
        System.out.println("1. 返回上一级");
        Scanner scanner = new Scanner(System.in);
        int choose = scanner.nextInt();
        while (choose != 1) {
            System.out.println("无效选择，请重新输入。");
            choose = scanner.nextInt();
        }
        if (choose == 1) {
            battleRequestHandler.showGameMenu(gameWebSocketClient);
        }
    }

    /**
     * 对服务端显示宠物的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    @Override
    public void showPets(GameWebSocketClient gameWebSocketClient, Result result) {
        JSONArray objects = JSONUtil.parseArray(result.getData());
        System.out.println("-----------查看宠物----------");
        for (int i = 0; i < objects.size(); i++) {
            Pet pet = objects.get(i, Pet.class);
            System.out.println(StrUtil.format("名称：{}，hp：{}，mp：{}，等级：{}，属性：{}"
                    , pet.getName()
                    , pet.getHp()
                    , pet.getMp()
                    , pet.getLevel()
                    , pet.getAttribute().getMain()));
        }
        System.out.println("-----------查看宠物----------");
        System.out.println("1. 返回上一级");
        Scanner scanner = new Scanner(System.in);
        int choose = scanner.nextInt();
        while (choose != 1) {
            System.out.println("无效选择，请重新输入。");
            choose = scanner.nextInt();
        }
        if (choose == 1) {
            battleRequestHandler.showGameMenu(gameWebSocketClient);
        }
    }

    /**
     * 对服务端显示背包商品列表的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    @Override
    public void showShop(GameWebSocketClient gameWebSocketClient, Result result) {
        JSONArray objects = JSONUtil.parseArray(result.getData());
        System.out.println("-----------查看商品----------");
        for (int i = 0; i < objects.size(); i++) {
            Goods goods = objects.get(i, Goods.class);
            System.out.println(StrUtil.format("id：{}，名称：{}，价格：{}，类型：{}，描述：{}"
                    , goods.getId()
                    , goods.getName()
                    , goods.getPrice()
                    , goods.getType()
                    , goods.getDescription()));
        }
        System.out.println("-----------查看商品----------");
        System.out.println("1. 返回上一级");
        System.out.println("2. 购买商品");
        Scanner scanner = new Scanner(System.in);
        int choose = scanner.nextInt();
        while (choose != 1 && choose != 2) {
            System.out.println("无效选择，请重新输入。");
            choose = scanner.nextInt();
        }
        if (choose == 1) {
            battleRequestHandler.showGameMenu(gameWebSocketClient);
        }
        if (choose == 2) {
            buyGoods(gameWebSocketClient, objects, result);
        }
    }

    /**
     * 对服务端购买成功的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    @Override
    public void handleBuy(GameWebSocketClient gameWebSocketClient, Result result) {
        System.out.println("购买成功");
        battleRequestHandler.showShop(gameWebSocketClient);
    }

    /**
     * 对服务端显示地图的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    @Override
    public void showMap(GameWebSocketClient gameWebSocketClient, Result result) {
        System.out.println("-----------探索地图----------");
        JSONArray objects = JSONUtil.parseArray(result.getData());
        for (int i = 0; i < objects.size(); i++) {
            Map map = objects.get(i, Map.class);
            System.out.println(StrUtil.format("id：{}，名称：{}"
                    , map.getId()
                    , map.getName()));
        }
        System.out.println("-----------探索地图----------");
        System.out.println("1. 返回上一级");
        System.out.println("2. 进入地图");
        Scanner scanner = new Scanner(System.in);
        int choose = scanner.nextInt();
        while (choose != 1 && choose != 2) {
            System.out.println("无效选择，请重新输入。");
            choose = scanner.nextInt();
        }
        if (choose == 1) {
            battleRequestHandler.showGameMenu(gameWebSocketClient);
            return;
        }
        if (choose == 2) {
            enterMap(objects, gameWebSocketClient, result);
            return;
        }
    }

    /**
     * 展示在线人数
     *
     * @param gameWebSocketClient
     * @param result
     */
    @Override
    public void showUserOnlineName(GameWebSocketClient gameWebSocketClient, Result result) {

        if (result.getStatus().equals(StatusConstant.SUCCESS)) {
            String userDate = (String) result.getData();
            String[] split = userDate.split(",");
            int userNum = split.length;

            System.out.println("--------当前在线人数：" + userNum + "-----------");
            for (int i = 0; i < userNum; i++) {
                System.out.println(split[i]);
            }
            System.out.println("-------------------------------------");

            new BattleRequestHandler().showGameMenu(gameWebSocketClient);

        }


    }

    /**
     * 完成捕捉宠物成功的回调
     * @param gameWebSocketClient
     * @param result
     */
    @Override
    public void toHandlePetFetch(GameWebSocketClient gameWebSocketClient, Result result) {
        if (result.getStatus().equals(StatusConstant.SUCCESS)) {
            FutureManager.completeFuture(UserContext.getCurrentUser(),"success");
        }else{
            FutureManager.completeFuture(UserContext.getCurrentUser(),"背包宠物已经达到6个或其他异常原因，捕获失败");
        }

    }

    /**
     * 对服务端进入地图的响应的处理
     *
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务端返回的结果
     */
    private void enterMap(JSONArray objects, GameWebSocketClient gameWebSocketClient, Result result) {
        System.out.println("输入要进入的地图id");
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        if (!checkMap(Long.parseLong(choose), objects)) {
            System.out.println("地图不存在");
            showMap(gameWebSocketClient, result);
            return;
        }
        Map map = getMapById(Long.parseLong(choose), objects);
        String title = StrUtil.format("-----------{}-----------", map.getName());
        System.out.println(title);
        for (Pet pet : map.getPets()) {
            System.out.println(StrUtil.format("{}.{}(lv{}) {}"
                    , pet.getId()
                    , pet.getName()
                    , pet.getLevel()
                    , pet.getAttribute().getMain()));
        }
        System.out.println("1.返回");
        System.out.println("2.战斗");
        choose = scanner.nextLine();
        if (choose.equals("1")) {
            showMap(gameWebSocketClient, result);
            return;
        }
        if (choose.equals("2")) {
            battle(map.getPets(), gameWebSocketClient, result);
            return;
        }
    }

    /**
     * 查询当前宠物是否存在
     *
     * @param id      宠物id
     * @param mapPets 宠物列表
     * @return 是否存在
     */
    private boolean checkPet(Long id, List<Pet> mapPets) {
        return mapPets.stream().anyMatch(pet -> pet.getId().equals(id));
    }

    /**
     * 根据宠物id获取宠物对象，服务端会返回一个地图宠物的全部信息，该方法是根据返回的信息进行二次查询
     *
     * @param id      宠物id
     * @param mapPets 地图宠物
     * @return 宠物对象
     */
    private Pet getPetById(Long id, List<Pet> mapPets) {
        for (int i = 0; i < mapPets.size(); i++) {
            if (mapPets.get(i).getId().equals(id)) {
                return mapPets.get(i);
            }
        }
        return null;
    }

    /**
     * 选择要出战的宠物
     *
     * @param mapPets             宠物列表
     * @param gameWebSocketClient 与服务端通信的对象
     * @param result              服务器返回的结果
     */
    private void battle(List<Pet> mapPets, GameWebSocketClient gameWebSocketClient, Result result) {
        System.out.println("选择对战的宠物id");
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        while (!checkPet(Long.parseLong(choose), mapPets)) {
            System.out.println("宠物不存在，请重新选择");
            choose = scanner.nextLine();
        }
        Pet pet = getPetById(Long.parseLong(choose), mapPets);
        battleV2(pet, gameWebSocketClient);
        FutureManager.registerFuture(UserContext.getCurrentUser(), new CompletableFuture<>());//注册异步处理器
        //回调
        FutureManager.getFuture(UserContext.getCurrentUser()).thenAccept(user -> {
            log.info("方法回调被执行");
            showMap(gameWebSocketClient, result);
        });
    }

    /**
     * 在与野生宠物对战阶段要执行的逻辑
     *
     * @param pet                 当前出战的宠物
     * @param gameWebSocketClient 与服务端通信的对象
     */
    private void battleV2(Pet pet, GameWebSocketClient gameWebSocketClient) {
        menu();
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        List<Pet> userPet = UserContext.getUserPet();
        Pet battle = null;
        while (!choose.equals("4") && !pet.dead() && !allDead(userPet)) {
            if (choose.equals("1")) {
                battle = chooseAndBattle(pet, gameWebSocketClient);
            } else if (choose.equals("2")) {
                if (battle != null) {
                    round(pet, battle, userPet, gameWebSocketClient);
                    if (pet.dead()) {
                        break;
                    }
                } else {
                    System.out.println("请选择你的宠物");
                }
            } else if (choose.equals("3")) {
                if (battle == null) {
                    System.out.println("请选择你的宠物");
                    menu();
                    choose = scanner.nextLine();
                    continue;
                }
                if (!checkBagNum()) {
                    System.out.println("道具数量不足");
                    continue;
                }
                boolean success = selectBag(pet, battle, gameWebSocketClient);
                if (success) {
                    break;
                }
            }
            menu();
            choose = scanner.nextLine();
        }
        if (allDead(userPet)) {
            System.out.println("所有宠物已阵亡");
        }
        recover(UserContext.getUserPet());
    }

    /**
     * 检查背包中是否有道具
     *
     * @return 布尔值
     */
    private boolean checkBagNum() {
        List<BagDTO> userBag = UserContext.getUserBag();
        if (userBag == null || userBag.size() == 0) {
            return false;
        }
        return userBag.stream().max(Comparator.comparingInt(BagDTO::getQuantity)).get().getQuantity() >= 1;
    }

    /**
     * @param pet
     * @param battle
     * @param gameWebSocketClient
     * @return
     */
    private boolean selectBag(Pet pet, Pet battle, GameWebSocketClient gameWebSocketClient) {
        List<BagDTO> userBag = UserContext.getUserBag();
        showBag(userBag);
        System.out.println("输入要使用的物品名称");
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        while (!checkBag(userBag, choose)) {
            System.out.println("物品不存在或数量不足，请重新选择");
            choose = scanner.nextLine();
        }
        BagDTO bag = getBag(userBag, choose);
        bag.setQuantity(bag.getQuantity() - 1);
        if (bag.getType().equals("道具")) {
            recover(battle, bag);
        } else if (bag.getType().equals("洛克球")) {
            boolean success = fetch(pet, bag, gameWebSocketClient);
            if (success) {
                System.out.println("捕获成功");
                return true;
            } else {
                System.out.println("捕获失败");
                return false;
            }
        }
        Random random = new Random();
        int s = random.nextInt(pet.getSkill().size());
        battle.attacked(pet.getSkill().get(s));
        System.out.println(
                StrUtil.format("{}使用了{}，攻击了{}，攻击力为{}，你剩余血量{}", pet.getName(),
                        pet.getSkill().get(s).getName(),
                        pet.getName(), pet.getSkill().get(s).getValue(), battle.getHp()));
        return false;
    }

    /**
     * 使用洛克球进行捕捉的相关逻辑代码
     *
     * @param pet                 宠物
     * @param bag                 背包
     * @param gameWebSocketClient 通信对象
     * @return 布尔值
     */
    private boolean fetch(Pet pet, BagDTO bag, GameWebSocketClient gameWebSocketClient) {
        boolean success = false;
        Random random = new Random();
        int i = random.nextInt(10);
        if (bag.getGoodsName().contains("初级")) {
            success = i < 3;
        } else if (bag.getGoodsName().contains("中级")) {
            success = i < 5;
        } else if (bag.getGoodsName().contains("高级")) {
            success = i < 7;
        }
        //如果捕捉成功则执行以下代码
        if (success) {
            //捕获成功后插入的时候把等级设置为1
            Pet pet1 = new Pet();
            BeanUtil.copyProperties(pet, pet1);
            pet1.setLevel(1);
            UserContext.getUserPet().add(pet1);
            Long id = UserContext.getUser().getId();
            List<BagDTO> userBag = UserContext.getUserBag();
            HashMap<String, String> req = new HashMap<>();
            req.put("id", id.toString());
            req.put("bag", JSONUtil.toJsonStr(userBag));
            req.put("pet", JSONUtil.toJsonStr(pet));
            req.put("index", String.valueOf(UserContext.getUserPet().size()));

            Result<String> request = new Result<>();
            request.setModuleName(ModuleTypeConstant.USER);
            request.setCommand(SubmoduleTypeConstant.PVE);
            request.setData(JSONUtil.toJsonStr(req));
            gameWebSocketClient.send(JSONUtil.toJsonStr(request));

        }
        return success;
    }

    /**
     * 对回血回蓝的相关操作
     *
     * @param battle
     * @param bagDTO
     */
    private void recover(Pet battle, BagDTO bagDTO) {
        if (bagDTO.getDescription().contains("回蓝")) {
            System.out.println(
                    StrUtil.format("{}使用了{}，回蓝{}点", battle.getName(), bagDTO.getGoodsName(), bagDTO.getValue()));
            battle.setMp(battle.getMp() + Integer.parseInt(bagDTO.getValue()));
        } else if (bagDTO.getDescription().contains("回血")) {
            System.out.println(
                    StrUtil.format("{}使用了{}，回血{}点", battle.getName(), bagDTO.getGoodsName(), bagDTO.getValue()));
            battle.setHp(battle.getHp() + Integer.parseInt(bagDTO.getValue()));
        }
    }

    /**
     * 拿到背包信息
     *
     * @param userBag
     * @param name
     * @return
     */
    private BagDTO getBag(List<BagDTO> userBag, String name) {
        for (int i = 0; i < userBag.size(); i++) {
            if (userBag.get(i).getGoodsName().equals(name)) {
                return userBag.get(i);
            }
        }
        return null;
    }

    /**
     * 检索背包信息是否存在
     *
     * @param userBag
     * @param name
     * @return
     */
    private boolean checkBag(List<BagDTO> userBag, String name) {
        BagDTO bag = getBag(userBag, name);
        return userBag.stream().anyMatch(bagDTO -> bagDTO.getGoodsName().equals(name)) && bag.getQuantity() >= 1;
    }

    /**
     * 展示pve对战中的背包信息
     *
     * @param userBag
     */
    private void showBag(List<BagDTO> userBag) {
        System.out.println("-----------背包-----------");
        for (int i = 0; i < userBag.size(); i++) {
            BagDTO bagDTO = userBag.get(i);
            System.out.println(StrUtil.format("名称：{}，类型：{}，数量：{}，描述：{}，价值:{}"
                    , bagDTO.getGoodsName()
                    , bagDTO.getType()
                    , bagDTO.getQuantity(),
                    bagDTO.getDescription(), bagDTO.getValue()));
        }
        System.out.println("-----------背包-----------");
    }

    /**
     * 默认100血100蓝
     *
     * @param userPet
     */
    private void recover(List<Pet> userPet) {
        userPet.forEach(pet -> {
            pet.setMp(100);
            pet.setHp(100);
        });
    }

    /**
     * pve对战过程中展示的菜单
     */
    private static void menu() {
        System.out.println("----------------------");
        System.out.println("1.选择宠物出战");
        System.out.println("2.继续战斗");
        System.out.println("3.背包");
        System.out.println("4.逃跑");
        System.out.println("----------------------");
    }

    /**
     * 返回选择的宠物
     *
     * @param pet
     * @param gameWebSocketClient
     * @return
     */
    private Pet chooseAndBattle(Pet pet, GameWebSocketClient gameWebSocketClient) {
        List<Pet> userPet = UserContext.getUserPet();
        showUserPet(userPet);
        System.out.println("选择你的宠物：");
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        while (!checkPet(Long.parseLong(choose), userPet)) {
            System.out.println("宠物不存在，请重新选择");
            choose = scanner.nextLine();
        }
        Pet battlePet = getPetById(Long.parseLong(choose), userPet);
        round(pet, battlePet, userPet, gameWebSocketClient);
        return battlePet;
    }

    /**
     * pve对战核心逻辑
     *
     * @param pet
     * @param battlePet
     * @param userPet
     * @param gameWebSocketClient
     */
    private void round(Pet pet, Pet battlePet, List<Pet> userPet, GameWebSocketClient gameWebSocketClient) {
        if (battlePet.dead()) {
            System.out.println("请更换宠物");
            chooseAndBattle(pet, gameWebSocketClient);
            return;
        }
        int i = 1;
        for (Skill skill : battlePet.getSkill()) {
            System.out.println(StrUtil.format("{}.技能：{}，mp：{}，value：{}", i, skill.getName(), skill.getNeedMp(),
                    skill.getValue()));
            i++;
        }
        System.out.println("选择使用的技能:");
        Scanner scanner = new Scanner(System.in);
        String choose = scanner.nextLine();
        while (Integer.parseInt(choose) > battlePet.getSkill().size() && battlePet.getMp() < battlePet.getSkill()
                .get(Integer.parseInt(choose)).getNeedMp()) {
            if (battlePet.getMp() < battlePet.getSkill().stream().max(Comparator.comparingInt(Skill::getNeedMp)).get()
                    .getNeedMp()) {
                System.out.println("mp不足，请更换宠物");
                chooseAndBattle(pet, gameWebSocketClient);
                return;
            }
            if (battlePet.getMp() < battlePet.getSkill()
                    .get(Integer.parseInt(choose)).getNeedMp()) {
                System.out.println("mp不足");
                choose = scanner.nextLine();
            } else {
                System.out.println("无效输入，重新输入");
                choose = scanner.nextLine();
            }
        }
        battlePet.setMp(battlePet.getMp() - battlePet.getSkill().get(Integer.parseInt(choose) - 1).getNeedMp());
        pet.attacked(battlePet.getSkill().get(Integer.parseInt(choose) - 1));
        System.out.println(StrUtil.format("你使用了{}，攻击了{}，攻击力为{}，剩余mp{}，对方剩余血量{}",
                battlePet.getSkill().get(Integer.parseInt(choose) - 1).getName(),
                pet.getName(), battlePet.getSkill().get(Integer.parseInt(choose) - 1).getValue(), battlePet.getMp(), pet.getHp()));
        if (pet.dead()) {
            System.out.println("你赢了");
            //赢了之后给客户端发送请求，增加经验值或等级
            // 生成 20 到 80 的随机整数
            int experience = (int) (Math.random() * (61)) + 20; // (80 - 20 + 1) = 61
            Result<Object> result = new Result<>();
            result.setModuleName(ModuleTypeConstant.BATTLE);
            result.setCommand(SubmoduleTypeConstant.EXPERIENCE);
            result.setFromUser(UserContext.getCurrentUser());
            result.setMessage(Integer.toString(experience));
            result.setData(battlePet.getId());
            gameWebSocketClient.send(JSONUtil.toJsonStr(result));
            return;
        }
        Random random = new Random();
        if (pet.getSkill().size() == 0) {
            System.out.println("对方宠物无技能,结束本回合");
            return;
        }
        int s = random.nextInt(pet.getSkill().size());
        battlePet.attacked(pet.getSkill().get(s));
        System.out.println(
                StrUtil.format("{}使用了{}，攻击了{}，攻击力为{}，你剩余血量{}", pet.getName(),
                        pet.getSkill().get(s).getName(),
                        battlePet.getName(), pet.getSkill().get(s).getValue(), battlePet.getHp()));

    }

    /**
     * 对所有宠物死亡情况的判断
     *
     * @param userPet
     * @return
     */
    private boolean allDead(List<Pet> userPet) {
        for (Pet item : userPet) {
            if (!item.dead()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 展示我的宠物
     *
     * @param userPet
     */
    private void showUserPet(List<Pet> userPet) {
        System.out.println("-----------我的宠物----------");
        for (int i = 0; i < userPet.size(); i++) {
            Pet item = userPet.get(i);
            String msg = StrUtil.format("id：{}，名称：{}，等级：{}，属性：{}，血量：{}，蓝量：{}"
                    , item.getId()
                    , item.getName()
                    , item.getLevel()
                    , item.getAttribute().getMain()
                    , item.getHp()
                    , item.getMp()
            );
            if (item.dead()) {
                msg += "， 状态：死亡";
            }
            System.out.println(msg);
        }
        System.out.println("-----------我的宠物----------");
    }

    /**
     * 通过地图ID拿到对应地图信息
     *
     * @param id
     * @param objects
     * @return
     */
    private Map getMapById(Long id, JSONArray objects) {
        for (int i = 0; i < objects.size(); i++) {
            Map map = objects.get(i, Map.class);
            if (map.getId().equals(id)) {
                return map;
            }
        }
        return null;
    }

    /**
     * 检查地图是否存在
     *
     * @param id
     * @param objects
     * @return
     */
    private boolean checkMap(Long id, JSONArray objects) {
        for (int i = 0; i < objects.size(); i++) {
            Map map = objects.get(i, Map.class);
            if (map.getId().equals(id)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理购买商品的逻辑
     *
     * @param gameWebSocketClient
     * @param objects
     * @param result
     */
    private void buyGoods(GameWebSocketClient gameWebSocketClient, JSONArray objects, Result result) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入购买的商品id和数量，用空格分开");
        String[] s = scanner.nextLine().split(" ");
        long choose = Long.parseLong(s[0]);
        int quantity = Integer.parseInt(s[1]);

        //检查商品id是否输入正确
        if (!checkGoods(choose, objects)) {
            System.out.println("商品不存在");
            showShop(gameWebSocketClient, result);
            return;
        }

        //如果出现钱不够的情况，购买失败
        if (!checkPrice(choose, objects, quantity)) {
            System.out.println("购买失败");
            showShop(gameWebSocketClient, result);
            return;
        }
        // 更新背包信息和用户数据
        Goods goods = getGoodsById(choose, objects);
        List<BagDTO> userBag = UserContext.getUserBag();
        for (BagDTO bagDTO : userBag) {
            if (bagDTO.getGoodsName().equals(goods.getName())) {
                bagDTO.setQuantity(bagDTO.getQuantity() + quantity);
                break;
            }
        }
        HashMap<String, String> map = new HashMap<>();
        User user = UserContext.getUser();
        user.setMoney(user.getMoney() - goods.getPrice() * quantity);
        UserContext.setUser(user);
        map.put("user", JSONUtil.toJsonStr(user));
        map.put("quantity", String.valueOf(quantity));
        map.put("goods", JSONUtil.toJsonStr(goods));
        Result<String> request = new Result<>();
        request.setModuleName(ModuleTypeConstant.USER);
        request.setCommand(SubmoduleTypeConstant.BUY);
        request.setData(JSONUtil.toJsonStr(map));
        gameWebSocketClient.send(JSONUtil.toJsonStr(request));
    }

    /**
     * 检查商品id是否存在
     *
     * @param id
     * @param objects
     * @return
     */
    private boolean checkGoods(Long id, JSONArray objects) {
        for (int i = 0; i < objects.size(); i++) {
            Goods goods = objects.get(i, Goods.class);
            if (goods.getId().equals(id)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查钱是否足够
     *
     * @param id
     * @param objects
     * @param quantity
     * @return
     */
    private boolean checkPrice(Long id, JSONArray objects, int quantity) {
        for (int i = 0; i < objects.size(); i++) {
            Goods goods = objects.get(i, Goods.class);
            if (goods.getId().equals(id)) {
                User user = UserContext.getUser();
                return user.getMoney() >= goods.getPrice() * quantity;
            }
        }
        return false;
    }

    /**
     * 通过id拿到对应商品
     *
     * @param id
     * @param objects
     * @return
     */
    private Goods getGoodsById(Long id, JSONArray objects) {
        for (int i = 0; i < objects.size(); i++) {
            Goods goods = objects.get(i, Goods.class);
            if (goods.getId().equals(id)) {
                return goods;
            }
        }
        return null;
    }
}
